package oa.hleast.xswl.service.pay.impl;

import cn.hutool.core.io.IoUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.xswl.service.pay.AlipayClientService;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@AllArgsConstructor
public class AlipayClientServiceImpl implements AlipayClientService {

    private static Map<String, AlipayClient> alipayClientMap = new HashMap<>();

    @Override
    public AlipayClient getAlipayClient(String alipayAppId, String alipayAppPrivateKey) {

        if (alipayClientMap.containsKey(alipayAppId)) {
            return alipayClientMap.get(alipayAppId);
        } else {

            // 文件路径
            String path = null;
            try {
                path = ResourceUtils.getURL("classpath:").getPath();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }

            log.info("path = {}", path);
            String crsPath = "devcsr" + File.separator;
            // 支付宝应用证书 绝对路径
            String alipayCertPath = crsPath + "appCertPublicKey_2021000118630363.crt";
            // 支付宝公钥证书 绝对路径
            String alipayCertPublicKeyPath = crsPath + "alipayCertPublicKey_RSA2.crt";
            // 支付宝根证书 绝对路径
            String alipayRootCertPath = crsPath + "alipayRootCert.crt";

//            String publicKey = null;
//            try {
//                publicKey = AlipaySignature.getAlipayPublicKey(alipayCertPath);
//            } catch (AlipayApiException e) {
//                e.printStackTrace();
//            }


            String serverUrl = "https://openapi.alipaydev.com/gateway.do";
            CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
            //gateway:支付宝网关（固定）https://openapi.alipay.com/gateway.do
            certAlipayRequest.setServerUrl(serverUrl);
            //APPID 即创建应用后生成,详情见创建应用并获取 APPID
            certAlipayRequest.setAppId(alipayAppId);
            //开发者应用私钥，由开发者自己生成
            certAlipayRequest.setPrivateKey(alipayAppPrivateKey);
            //参数返回格式，只支持 json 格式
            certAlipayRequest.setFormat("json");
            //请求和签名使用的字符编码格式，支持 GBK和 UTF-8
            certAlipayRequest.setCharset("UTF-8");
            //商户生成签名字符串所使用的签名算法类型，目前支持 RSA2 和 RSA，推荐商家使用 RSA2。
            certAlipayRequest.setSignType("RSA2");
            //应用公钥证书路径（app_cert_path 文件绝对路径）
//            certAlipayRequest.setCertPath(alipayCertPath);
            //支付宝公钥证书文件路径（alipay_cert_path 文件绝对路径）
//            certAlipayRequest.setAlipayPublicCertPath(alipayCertPublicKeyPath);
            //支付宝CA根证书文件路径（alipay_root_cert_path 文件绝对路径）
//            certAlipayRequest.setRootCertPath(alipayRootCertPath);
            AlipayClient alipayClient = null;
            try {

                Resource certResource = new ClassPathResource(alipayCertPath);
                String certContent = IoUtil.read(certResource.getInputStream(), "utf-8");
                certAlipayRequest.setCertContent(certContent);

                Resource alipayCertResource = new ClassPathResource(alipayCertPublicKeyPath);
                String alipayCertContent = IoUtil.read(alipayCertResource.getInputStream(), "utf-8");
                certAlipayRequest.setAlipayPublicCertContent(alipayCertContent);

                Resource alipayRootResource = new ClassPathResource(alipayRootCertPath);
                String alipayRootContent = IoUtil.read(alipayRootResource.getInputStream(), "utf-8");
                certAlipayRequest.setRootCertContent(alipayRootContent);

                // 请求网关 (gateway)、应用 id (app_id)、应用私钥 (private_key)、编码格式 (charset)、支付宝公钥 (alipay_public_key)、签名类型 (sign_type)
//            alipayClient = new DefaultAlipayClient(serverUrl, ALIPAY_APP_ID, ALIPAY_APP_PRIVATE_KEY, "json", "UTF-8", publicKey, "RSA2");
                alipayClient = new DefaultAlipayClient(certAlipayRequest);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("{}", e.getMessage(), e);
                throw new BizException("系统异常");
            }

            return alipayClient;
        }

    }
}
